package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.RebateMapper;
import com.yami.shop.dao.RebateRecordsMapper;
import com.yami.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class RebateRecordsServiceImpl extends ServiceImpl<RebateRecordsMapper, RebateRecords> implements RebateRecordsService {

    @Autowired
    private RebateMapper rebateMapper;

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ProductService productService;
    @Autowired
    private RebateService rebateService;
    @Autowired
    private RebateRecordsService rebateRecordsService;
    @Autowired
    private RebateRecordsMapper rebateRecordsMapper;
    @Autowired
    private UserService userService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealRebate(String orderNumber,String userId) {
        //根据订单编号,查询购买的商品是否是推广的商品
       List<OrderItem> orderItemList =  orderItemService.getOrderItemsByOrderNumber(orderNumber);
       for(OrderItem orderItem:orderItemList){
           if(orderItem!=null){
               Long proId  = orderItem.getProdId();
               Double totalAmount = orderItem.getPrice();
               if(proId!=null){
                   //查询当前商品是否是推广池的商品
                  Product product = productService.getProductByProdId(proId);
                  if(product!=null){
                      int spread =  product.getIsSpread();
                      //店铺信息
                      Long shopId = product.getShopId();
                      if(spread==0){
                          //如果是推广池的商品,则去查询返利规则下该商品返利规则,看是否有对应的返利规则
                         Rebate rebate = rebateService.getRebate(shopId,proId);
                         if(rebate!=null){
                              //返利规则可以查询到当前商品，说明可以对该用户的上级进行返利
                             this.insertRebateRecords(shopId,totalAmount,orderNumber,rebate,userId);
                         }
                      }
                  }
               }
           }
       }
    }

    /**
     * 新增一条返利信息,状态为待支付状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void  insertRebateRecords(Long shopId,Double totalAmount,String orderNumber,Rebate rebate,String userId){
        int type = rebate.getType();
        Double amount = rebate.getAmount();
        if(type==1){
            //百分比返利
            Double flmoney = Arith.mul(totalAmount,amount);
            //生成返利信息
            RebateRecords rebateRecords = new RebateRecords();
            rebateRecords.setShopId(shopId);
            rebateRecords.setAmount(flmoney);
            rebateRecords.setUserId(userId);
            rebateRecords.setOrderNumber(orderNumber);
            rebateRecords.setStatus(0);
            rebateRecords.setType(0);
            rebateRecords.setCreateTime(new Date());
            rebateRecordsService.save(rebateRecords);
        }
    }

    /**
     * 当订单完成后  修改返利状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealRebateAfterOrder(List<Order> orders) {
        for(Order order:orders){
            if(order!=null){
                //获得订单推荐人
                String tjr = order.getTjr();
                String tjrUserId=null;
                if(null!=tjr&&!"".equals(tjr)){
                     tjrUserId = userService.getUserByAppConnectId(Long.valueOf(tjr));
                }
                //获取订单编号
                String orderNumber = order.getOrderNumber();
                //查询当前订单有没有待结算的返利信息
               RebateRecords rebateRecords = rebateRecordsMapper.getRebateRecords(orderNumber);
               if(rebateRecords!=null){
                   //获取下单用户
                   String orderUserId = order.getUserId();
                   //绑定下单用户的上级
                   User orderUser = userService.getUserByUserId(orderUserId);
                   //推荐用户
                   User tjUser = userService.getUserByUserId(tjrUserId);
                   if(orderUser.getPuserid()==null||"".equals(orderUser.getPuserid())) {
                       if(!tjrUserId.equals(orderUserId)) {
                           if(tjUser.getPuserid()==null||!tjUser.getPuserid().equals(orderUserId)){
                               orderUser.setPuserid(tjrUserId);
                               userService.saveOrUpdate(orderUser);
                           }
                       }
                   }
                   //获取返利的用户
                   String userId = rebateRecords.getUserId();
                    //返利金额
                    Double  at =  rebateRecords.getAmount();
                    rebateRecords.setStatus(2);
                    rebateRecords.setUpdateTime(new Date());
                    rebateRecordsService.updateById(rebateRecords);
                    User user = userService.getUserByUserId(userId);
                    Double account = user.getAccount();
                    if(account!=null){
                        Double cueentAccount = Arith.add(account,at);
                        user.setAccount(cueentAccount);
                        userService.updateById(user);
                    }
               }
            }
        }

    }



}
